//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends egret.DisplayObjectContainer {

    /**
     * 加载进度界面
     * Process interface loading
     */
    private loadingView: LoadingUI;

    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
    }

    private onAddToStage(event: egret.Event) {
        //设置加载进度界面
        //Config to load process interface
        this.loadingView = new LoadingUI();
        this.stage.addChild(this.loadingView);

        //初始化Resource资源加载库
        //initiate Resource loading library
        RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.loadConfig("resource/default.res.json", "resource/");
    }

    /**
     * 配置文件加载完成,开始预加载preload资源组。
     * configuration file loading is completed, start to pre-load the preload resource group
     */
    private onConfigComplete(event: RES.ResourceEvent): void {
        RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
        RES.loadGroup("preload");
    }

    /**
     * preload资源组加载完成
     * Preload resource group is loaded
     */
    private onResourceLoadComplete(event: RES.ResourceEvent) {
        if (event.groupName == "preload") {
            this.stage.removeChild(this.loadingView);
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
            RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);

            //初始化开始游戏
            this.init();
        }
    }

    private bottom: number = 416;   //对其底部坐标
    private boy: egret.Bitmap;      //小男孩
    private finish: egret.Bitmap;   //终点线
    private objs: Array<egret.Bitmap> = new Array();

    /*
    *  
    *  初始化游戏
    */
    private init(): void {
        //添加背景
        for (var i: number = 0; i < 4; i++) {
            var bg: egret.Bitmap = this.createBitmapByName("tile_bg");
            this.addChild(bg);
            bg.x = bg.width * i;
        }

        //增加障碍物
        for (var i: number = 1; i < 4; i++) {
            var obj: egret.Bitmap = this.createBitmapByName("object_0" + i);
            this.addChild(obj);
            obj.x = 150 + 200 * i;
            obj.y = this.bottom - obj.height;
            this.objs.push(obj);
        }


        //添加 终点线
        this.finish = this.createBitmapByName("finish");
        this.addChild(this.finish);//默认左上角
        this.finish.x = 1000;
        this.finish.y = this.bottom - this.finish.height;

        //开始
        this.startTip = this.createBitmapByName("tapToStart");
        this.addChild(this.startTip);//默认左上角
        this.startTip.x = 200;
        this.startTip.y = this.bottom - this.startTip.height - 50;

        //跳跃
        this.jumpTip = this.createBitmapByName("tapToJump");
        this.addChild(this.jumpTip);//默认左上角
        this.jumpTip.x = 300;
        this.jumpTip.y = this.bottom - this.jumpTip.height - 50;
        this.jumpTip.visible = false;


        //添加 boy
        this.boy = this.createBitmapByName("green_boy");
        this.addChild(this.boy);//默认左上角
        this.boy.x = 200;
        this.boy.y = this.bottom - this.boy.height;

        //监听事件
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTouchBegin, this);

        //需要 TOUCH_BEGIN 事件时，需要启用；默认不启用 可以提升程序性能。
        this.touchEnabled = true;

    }

    //检测 obj 有没有 碰到 boy
    private testBoy(obj: egret.Bitmap): boolean {
        return obj.hitTestPoint(this.boy.x + this.boy.width * 0.5, this.boy.y + this.boy.height * 0.5);
    }
    
    private vx: number = 0;     // x轴坐标
    private vy: number = 0;     // y轴速度
    private g: number = 0.98;   // 重力加速度
    private isJumping: boolean = false; //是否处理跳起过程中

    /**   
      帧频事件 改变 x 

      小男孩 移动事件；     
    */
    private onEnterFrame(event: egret.Event): void {
        //游戏
        if (!this.started || this.gameOver) return;

        this.vy += this.g;
        this.boy.x += this.vx;
        this.boy.y += this.vy;

        //当落地后，vy置为0
        if (this.boy.y > this.bottom - this.boy.height) {
            this.boy.y = this.bottom - this.boy.height;
            this.isJumping = false;
            this.vy = 0;
        }

        //检测有没有 碰到障碍物
        this.testObjects();
    }

    private started: boolean = false;   //游戏是否已开始
    private startTip: egret.Bitmap;
    private jumpTip: egret.Bitmap;

    private gameOver: boolean = false;

    //触摸跳跃事件 （鼠标单击）
    private onTouchBegin(event: egret.TouchEvent): void {

        if (!this.started) {
            this.startTip.visible = false;
            this.jumpTip.visible = true;
            this.started = true;
            this.vx = 2;
            return;
        }

        //游戏结束，重置状态
        if (this.gameOver) {
            this.boy.x = 200;
            this.boy.y = this.bottom - this.boy.height;
            this.jumpTip.visible = false;
            this.startTip.visible = true;
            this.started = false;
            this.gameOver = false;
            return;
        }

        if (!this.isJumping) {
            this.jumpTip.visible = false;
            this.isJumping = true;
            this.vy = -14;
        }
    }

    private testObjects(): void {
        for (var i: number = 0; i < this.objs.length; i++) {
            var obj: egret.Bitmap = this.objs[i];
            if (this.testBoy(obj)) {
                this.gameOver = true;
            }
        }
    }


    /**
     * 资源组加载出错
     *  The resource group loading failed
     */
    private onItemLoadError(event: RES.ResourceEvent) {
        console.warn("Url:" + event.resItem.url + " has failed to load");
    }

    /**
     * 资源组加载出错
     *  The resource group loading failed
     */
    private onResourceLoadError(event: RES.ResourceEvent) {
        //TODO
        console.warn("Group:" + event.groupName + " has failed to load");
        //忽略加载失败的项目
        //Ignore the loading failed projects
        this.onResourceLoadComplete(event);
    }

    /**
     * preload资源组加载进度
     * Loading process of preload resource group
     */
    private onResourceProgress(event: RES.ResourceEvent) {
        if (event.groupName == "preload") {
            this.loadingView.setProgress(event.itemsLoaded, event.itemsTotal);
        }
    }

    /**
     * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
     * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
     */
    private createBitmapByName(name: string) {
        let result = new egret.Bitmap();
        let texture: egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;
    }
  
}


